package com.briup.estore.common.utils;

import com.briup.estore.common.exception.EstoreException;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @Author briup-adam
 * @Date 2023/8/1 上午9:10
 * @Description 实体对象拷贝工具类
 **/

public class BeanCopyUtils {

    public static <T> T copyBean(Object source, Class<T> targetClass) {
        T instance = null;
        Class<?> sourceClass = source.getClass();
        //获取源对象的所有属性以及属性值
        Field[] sourceClassFields = sourceClass.getDeclaredFields();

        //创建map集合 存放属性名以及属性值
        HashMap<String, Object> map = new HashMap<>();


        try {
            for (Field field : sourceClassFields) {
                field.setAccessible(true);
                Object o = field.get(source);
                map.put(field.getName(),o);
            }
            //使用该类的默认无参构造器创建对象
            instance = targetClass.newInstance();
            //获取所有属性
            Field[] fields = targetClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object o = map.get(field.getName());
                if (Objects.isNull(o)){
                   continue;
                }

                field.set(instance,o);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return instance;
    }

    public  static  <T> List<T> copyList(List list,Class<T> c){
        ArrayList<T> ts = new ArrayList<>();
        list.forEach(i->{
            T t = copyBean(i, c);
            ts.add(t);
        });
        return  ts;
    }
}
